package com.itheima.web;

import com.itheima.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class ImageController {
    @Value("${FileDir}")
    private String fileDir;
    @PostMapping(value = "/upload")
    public R upload(MultipartFile file) throws IOException {
        File file1 = new File(fileDir);
        if (!file1.exists()){
            file1.mkdirs();
        }
        String s = UUID.randomUUID().toString().replaceAll("-","")+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        file.transferTo(new File(fileDir+s));
        return R.success(s);
    }
    @GetMapping("/download")
    public R download(String name, HttpServletResponse resp) throws IOException {
        OutputStream os = resp.getOutputStream();
        File file = new File(fileDir + name);
        FileInputStream is = new FileInputStream(fileDir + name);
        IOUtils.copyLarge(is,os);
        is.close();
        os.close();
        return R.success("下载成功！");
    }
}
